<template>
  <div class="userInfo shadow" :style="style">
    <div class="bg">
      <div></div>
    </div>
    <div class="info">
      <div class="left">
        <div class="avatar">
          <el-upload
            class="avatar-uploader2"
            action="/resource/resources/upload"
            :show-file-list="false"
            :headers="upheader"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="form.headImg"
              fit="cover"
              :src="'/file/' + form.headImg"
              class="avatar2"
            ></el-image>
            <el-image
              v-else
              fit="cover"
              src="https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"
              class="avatar2"
            ></el-image>
          </el-upload>
        </div>
        <div class="form-bg">
          <div class="form">
            <el-form
              ref="form"
              label-width="80px"
              :rules="rules1"
              :inline="false"
              label-position="top"
              :model="form"
            >
              <el-form-item
                prop="name"
                :rules="[
                  { required: true, message: '请输入名称', trigger: 'change' },
                ]"
              >
                <span slot="label" style="color: #ff0000">名称</span>
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item
                prop="phoneNum"
                :rules="[
                  {
                    required: true,
                    message: '请输入手机号',
                    trigger: 'change',
                  },
                ]"
              >
                <span slot="label" style="color: #ff0000">手机号</span>
                <el-input v-model="form.phoneNum" type="Number"></el-input>
              </el-form-item>
              <el-form-item>
                <span slot="label">手写签名</span>
                <el-upload
                  class="avatar-uploader"
                  action="/resource/resources/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="upheader"
                >
                  <img
                    v-if="form.signatureImg"
                    :src="'/file/' + form.signatureImg"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item prop="name">
                <span slot="label" style="color: #ff0000">个人积分</span>
                <el-input
                  v-model="totalIntergal"
                  style="width: 70px"
                  disabled
                ></el-input>
                <el-button class="bottom_all" @click="handleDetails"
                  >查看明细</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button
                  class="bottom_all"
                  style="margin: 20px 0 0 0; width: 100%; height: 44px"
                  @click="submit2"
                  >保存信息</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="form">
          <el-form
            ref="form2"
            label-width="80px"
            :rules="rules2"
            :model="form2"
            :inline="false"
            label-position="top"
          >
            <el-form-item prop="oldPassword">
              <span slot="label">原密码</span>
              <el-input
                v-model="form2.oldPassword"
                type="password"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item prop="newPassword">
              <span slot="label">新密码</span>
              <el-input
                v-model="form2.newPassword"
                type="password"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <span slot="label">确认密码</span>
              <el-input
                v-model="form2.checkPass"
                type="password"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                class="bottom_all"
                style="margin: 20px 0 0 0; width: 100%; height: 44px"
                @click="submit"
                >提 交</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="visible" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">积分明细</span>
      <div class="dialoginfo">
        <div v-loading="tableLoading">
          <el-table
            :header-cell-style="{ background: '#f3f6f9' }"
            :cell-style="{ borderRight: 'none' }"
            border
            stripe
            style="width: 100%"
            :data="dataSource"
            tooltip-effect="dark"
          >
            <el-table-column
              prop="businessName"
              label="积分业务"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="sortProperty"
              label="兑换商品"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="intergalCount"
              label="积分变更"
              align="center"
            >
              <template slot-scope="scope">
                {{ "+" + scope.row.intergalCount }}
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="时间"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
        <div>
          <div style="display: flex; align-items: center">
            <div class="top_page_totle">总共{{ total }}条</div>
            <el-pagination
              :current-page.sync="page"
              :page-size="10"
              layout="prev,pager,next"
              :total="total"
              @current-change="getDetials()"
            ></el-pagination>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="visible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  update_password,
  updateSignature,
  getTotalIntergal,
  pageIntergalDetails,
} from "@/api/api.js";
import { getUserInfo } from "@/utils/auth.js";
import { getToken, getUserId } from "@/utils/auth";
export default {
  data() {
    var newPass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码至少6位"));
        return;
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form2.checkPass !== "") {
          this.$refs.form2.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form2.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      imageUrl: "",
      visible: false,
      totalIntergal: 0,
      screenHeight: 0,
      total: 0,
      name: "",
      userinfo: {},
      form: {
        name: "",
        phoneNum: "",
        signatureImg: "",
        headImg: "",
      },
      form2: {
        newPassword: "",
        checkPass: "",
        oldPassword: "",
      },
      rules1: {},
      rules2: {
        oldPassword: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        newPassword: [
          {
            validator: newPass,
            trigger: "blur",
          },
        ],
      },
      dataSource: [],
      page: 1,
      tableLoading: false,
    };
  },
  methods: {
    submit() {
      this.$refs.form2.validate(async (valid) => {
        if (valid) {
          this.form2.userName = await getUserInfo().loginAccount;
          update_password(this.form2).then((res) => {
            if (res.code == 1001) {
              this.$message({
                message: "密码修改成功",
                type: "success",
              });
              this.$store.dispatch("user/logout").then(() => {
                const urlList = window.localStorage.getItem("urlList");
                sessionStorage.clear();
                localStorage.clear();
                window.localStorage.setItem("urlList", urlList);
                this.$router.push("/login");
              });
            }
          });
        }
      });
    },
    submit2() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.headImg) {
            this.form.headImg = `${this.form.headImg}?type=img`;
          }
          updateSignature(this.form).then((res) => {
            if (res.code == 1001) {
              this.$message({
                message: "修改成功,重新登录后生效！",
                type: "success",
              });
              let UserInfo = JSON.parse(
                window.localStorage.getItem("userInfo")
              );
              UserInfo.userRealName = this.form.name;
              UserInfo.phoneNum = this.form.phoneNum;
              UserInfo.headImg = this.form.headImg;
              window.localStorage.setItem("userInfo", JSON.stringify(UserInfo));
            }
          });
        } else {
          return false;
        }
      });
    },
    handleDetails() {
      this.getDetials();
      this.page = 1;
      this.visible = true;
    },
    getDetials() {
      this.tableLoading = true;
      pageIntergalDetails({ page: this.page, pageSize: 10 }).then((res) => {
        console.log(res);
        if (res.code === 1001) {
          this.dataSource = res.data.data;
          this.total = res.data.totalRows;
          this.tableLoading = false;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /**签名*/
    handleAvatarSuccess(res) {
      if (res.code === 1001) {
        this.form.signatureImg = res.data.fileUrl;
      }
    },
    handleAvatarSuccess2(res) {
      if (res.code === 1001) {
        this.form.headImg = res.data.fileUrl;
      }
    },
    initIntergal() {
      getTotalIntergal().then((res) => {
        if (res.code === 1001) {
          this.totalIntergal = res.data.totalIntergal;
        }
      });
    },
  },
  computed: {
    style() {
      return "height:" + (this.screenHeight - 135) + "px;";
    },
  },
  async created() {
    this.screenHeight = document.documentElement.clientHeight;
    window.onresize = () => {
      return (() => {
        this.screenHeight = document.documentElement.clientHeight;
      })();
    };
    this.form.id = await getUserInfo().userId;
    this.form.name = await getUserInfo().userRealName;
    this.form.phoneNum = await getUserInfo().phoneNum;
    this.form.signatureImg = await getUserInfo().signatureImg;
    this.form.headImg = await getUserInfo().headImg;
    this.form2 = { ...this.form2, ...(await getUserInfo()) };
    this.initIntergal();
  },
};
</script>

<style lang="scss" scoped>
.userInfo {
  margin: 10px;
  background: #ffffff;
  border-radius: 4px;
  overflow: auto;
}
.bg {
  height: 163px;
  width: 100%;
  background: url(../../../assets/login/login.png) no-repeat;
  background-size: 100% auto;
  background-position: center right;
  position: relative;
  > div {
    position: absolute;
    left: 0;
    top: 0;
    height: 163px;
    width: 100%;
    background: rgb(255, 255, 255, 0.4);
  }
}
.info {
  min-height: calc(100% - 163px);
  display: flex;
  .left {
    flex: 2;
    border-right: 1px solid #e1e5ed;
    .form-bg {
      position: relative;
      height: 300px;
    }
    .form {
      width: 191px;
      position: absolute;
      top: 0px;
      left: 50%;
    }
    .avatar {
      position: relative;
      height: 100px;
    }
    .avatar-uploader2 {
      width: 148px;
      height: 148px;
      border-radius: 50%;
      position: absolute;
      top: -79px;
      left: 50%;
    }
  }
  .right {
    flex: 3;
  }
}
.right {
  padding: 20px 48px;
  .form {
    width: 503px;
  }
}
.avatar-uploader2 .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon2 {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar2 {
  width: 148px;
  height: 148px;
  border: 4px solid #ffffff;
  border-radius: 50%;
}
</style>
